package com.capgemini.rdlgae.servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.capgemini.rdlgae.util.MailUtils;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.apphosting.api.DatastorePb.DatastoreService;

public class Send extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2603189405942543736L;
	private static Logger log = Logger.getLogger(Send.class.getName());

	public void init() {
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		String dateCommande = req.getParameter("dateCommande");
		String to = req.getParameter("to");
		String cc = req.getParameter("cc");
		String fromLabel = req.getParameter("fromLabel");
		String subject = req.getParameter("subject");
		String content = req.getParameter("content");

		try {
			SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");
			Date date = sdf.parse(dateCommande);

			MailUtils.send(to, cc, fromLabel, subject, content);

			Query q = new Query("Order");
			q.addFilter("date", FilterOperator.EQUAL, date);
			Entity entity = DatastoreServiceFactory.getDatastoreService()
					.prepare(q).asSingleEntity();

			if (entity == null) {
				entity = new Entity("Order");
				entity.setProperty("date", date);
				entity.setProperty("lu", false);
				DatastoreServiceFactory.getDatastoreService().put(entity);
			}

			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.severe(e.getMessage());
			resp.setStatus(400);
		}

	}
}